package com.one.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.pojo.*;
import com.one.service.*;
import com.one.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description  会员管理
 * @Author semstouch
 * @Date 2017/4/7
 **/
@Controller
@ControllerAdvice
public class OneUserController extends AbstractJsonpResponseBodyAdvice {
    @Resource
    private OneUserService oneUserService;
    @Resource
    private NoticeService noticeService;
    @Resource
    private LandService landService;
    @Resource
    private StoreService storeService;
    @Resource
    private OneSuperService oneSuperService;

    public OneUserController() {
        super("callback");
    }

    @Resource(name="ehcacheCacheProvider")
    private EhcacheCacheProvider cacheProvider;

    /**
     * 获取注册短信验证码
     * @param request
     * @return
     */
    @RequestMapping(value = "/getVcode", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getVcode(HttpServletRequest request){
        JSONResult jsonResult = new JSONResult();

        String jsonStr = request.getParameter("jsonStr");
        ObjectMapper mapper = new ObjectMapper();
        Map oneUser = new HashMap();
        try {
            oneUser = mapper.readValue(jsonStr, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(oneUserService.findByPhone(oneUser.get("phone").toString())!=null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机号码已存在！");
            return jsonResult;
        }

        String actionId = StringUtils.getUUID();
        String VCode=SMSWebChinese.sendSMS(oneUser.get("phone").toString());
        if(VCode==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("发送短信验证码出错！");
            return jsonResult;
        }

        //发送短信验证码
        oneUser.put("vCode",VCode);

        cacheProvider.put(actionId,oneUser);

        jsonResult.setCode("1");
        jsonResult.setData(actionId);
        return jsonResult;
    }

    /**
     * 获取忘记密码短信验证码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/getVCode", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getVCode(String phone){
        JSONResult jsonResult = new JSONResult();

        if(oneUserService.findByPhone(phone)==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机号码为注册！");
            return jsonResult;
        }

        String actionId = StringUtils.getUUID();
        //发送短信验证码

        String VCode=SMSWebChinese.sendSMS(phone);
        if(VCode==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("发送短信验证码出错！");
            return jsonResult;
        }
        cacheProvider.put(actionId,VCode);

        jsonResult.setCode("1");
        jsonResult.setData(actionId);
        return jsonResult;
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult forgetPassword(HttpServletRequest request,String vCode,String  phone,String actionId,String newPassword) {
        JSONResult jsonResult = new JSONResult();
        if(!cacheProvider.get(actionId).equals(vCode)){
            jsonResult.setCode("-1");
            jsonResult.setMsg("验证失败，请重新发起验证|Validation failed, please restart validation");
            return jsonResult;
        }
        cacheProvider.remove(actionId);
        OneUser oneUser=oneUserService.findByPhone(phone);
        if(oneUser==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机帐号未注册！");
            return jsonResult;
        }
        oneUser.setPassword(newPassword);
        oneUserService.updateOneUser(oneUser);
        jsonResult.setCode("1");
        jsonResult.setMsg("成功|success");

        return jsonResult;
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult updatePassword(HttpServletRequest request,String token,String  userId) {
        JSONResult jsonResult = new JSONResult();
        if(!cacheProvider.get(userId).equals(token)){
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        OneUser oneUser=oneUserService.findByUserId(userId);
        if(oneUser.getPassword().equals(oldPassword)){
            oneUser.setPassword(newPassword);
            oneUserService.updateOneUser(oneUser);
            jsonResult.setCode("1");
            jsonResult.setMsg("成功|success");
        }else {
            jsonResult.setCode("-1");
            jsonResult.setMsg("密码错误|Password error");
        }
        return jsonResult;
    }

    /**
     * 更新帐号信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult updateUser(HttpServletRequest request,String token,String  userId) {
        JSONResult jsonResult = new JSONResult();
        if(!cacheProvider.get(userId).equals(token)){
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        String type = request.getParameter("type");
        String status = request.getParameter("status");
        OneUser oneUser=oneUserService.findByUserId(userId);
        if(type.equals("1")){
            oneUser.setMusicFlag(status);
        }

        if(type.equals("2")){
            oneUser.setSoundFlag(status);
        }

        if(type.equals("3")){
            oneUser.setUserPic(status);
        }
        oneUserService.updateOneUser(oneUser);
        jsonResult.setCode("1");
        jsonResult.setMsg("成功|success");
        return jsonResult;
    }

    /**
     * 激活帐号
     * @param request
     * @return
     */
    @RequestMapping(value = "/userActive", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult userActive(HttpServletRequest request,String token,String  userId,String phone) {
        JSONResult jsonResult = new JSONResult();
        if(!cacheProvider.get(userId).equals(token)){
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        OneUser oneUser= oneUserService.findByPhone(phone);
        OneUser activeUser= oneUserService.findByUserId(userId);
        if(oneUser==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("激活用户不存在!");
            return jsonResult;
        }

        Store activeStore =storeService.findByUserId(userId);
        Store store = storeService.findByUserId(oneUser.getUserId());
        if(activeStore.getChicksNum().intValue()<330){
            jsonResult.setCode("-1");
            jsonResult.setMsg("仓库小鸡数不够|Your chicken is not enough");
            return  jsonResult;
        }

        BigDecimal activeChicksNum = activeStore.getChicksNum().subtract(new BigDecimal(330));
        activeStore.setChicksNum(activeChicksNum);

        BigDecimal chicksNum = store.getChicksNum().add(new BigDecimal(300));
        store.setChicksNum(chicksNum);

        UserTrasRecord userTrasRecord = new UserTrasRecord();
        userTrasRecord.setId(StringUtils.getUUID());
        userTrasRecord.setSenderId(activeUser.getUserId());
        userTrasRecord.setReceiveId(oneUser.getUserId());
        userTrasRecord.setGiftType("3");
        userTrasRecord.setGiftNum(new BigDecimal(300));
        userTrasRecord.setFeeNum(new BigDecimal(30));
        userTrasRecord.setLoginName(activeUser.getLoginName());
        userTrasRecord.setStatus("1");
        userTrasRecord.setCreateTime(StringUtils.getNowTime());


        oneUser.setUserStatus("1");

        oneUserService.userActive(oneUser,store,activeStore,userTrasRecord);
        jsonResult.setCode("1");
        return jsonResult;
    }

    /**
     * 帮好友开通帐号
     * @param request
     * @return
     */
    @RequestMapping(value = "/userRegister", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult userRegister(HttpServletRequest request,String token) {
        JSONResult jsonResult = new JSONResult();

        String jsonStr = request.getParameter("jsonStr");
        ObjectMapper mapper = new ObjectMapper();
        Map params = new HashMap();
        try {
            params = mapper.readValue(jsonStr, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(!cacheProvider.get(params.get("registeUserId").toString()).equals(token)){
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }

        OneUser registerUser = oneUserService.findByUserId(params.get("registeUserId").toString());
        if(oneUserService.findByPhone(params.get("phone").toString())!=null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机号码已存在！");
            return jsonResult;
        }
        if(oneUserService.findByLoginName(params.get("loginName").toString())!=null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("用户名已存在！");
            return jsonResult;
        }


        Store registerStore = storeService.findByUserId(registerUser.getUserId());
        if(registerStore.getChicksNum().intValue()<330){
            jsonResult.setCode("-1");
            jsonResult.setMsg("仓库小鸡数不够|Your chicken is not enough");
            return  jsonResult;
        }
        OneUser oneUser = new OneUser();
        oneUser.setPhone(params.get("phone").toString());
        oneUser.setLoginName(params.get("loginName").toString());
        oneUser.setWeixin(params.get("weixin").toString());
        oneUser.setZhifubao(params.get("zhifubao").toString());
        oneUser.setGender(params.get("gender").toString());
        oneUser.setUserName(params.get("userName").toString());
        oneUser.setPassword("e10adc3949ba59abbe56e057f20f883e");
        //发送短信告知初始密码


        oneUser.setUserStatus("1");
        oneUser.setUpperUserRefId(registerUser.getUserRefId());

        UserTrasRecord userTrasRecord = new UserTrasRecord();
        userTrasRecord.setId(StringUtils.getUUID());
        userTrasRecord.setSenderId(registerUser.getUserId());
        userTrasRecord.setGiftType("3");
        userTrasRecord.setGiftNum(new BigDecimal(300));
        userTrasRecord.setFeeNum(new BigDecimal(30));
        userTrasRecord.setLoginName(registerUser.getLoginName());
        userTrasRecord.setStatus("1");
        userTrasRecord.setCreateTime(StringUtils.getNowTime());

        oneUserService.addOneUserAndStore(oneUser,registerStore,userTrasRecord);

        jsonResult.setCode("1");
        return jsonResult;
    }


    /**
     * 立即注册
     * @param request
     * @return
     */
    @RequestMapping(value = "/openRegister", method = RequestMethod.GET)
       @ResponseBody
       public JSONResult openRegister(HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        String actionId = request.getParameter("actionId");
        String vCode = request.getParameter("vCode");
        Map oneUser = new HashMap();
        oneUser = (Map) cacheProvider.get(actionId);
        String sendVCode=(String)oneUser.get("vCode");

        if(!vCode.equals(sendVCode)){
            jsonResult.setCode("-1");
            jsonResult.setMsg("验证失败，请重新发起验证|Validation failed, please restart validation");
            return jsonResult;
        }
        if(oneUserService.findByLoginName(oneUser.get("loginName").toString())!=null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("用户名已存在！");
            return jsonResult;
        }
        if(oneUserService.findByPhone(oneUser.get("phone").toString())!=null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机号码已存在！");
            return jsonResult;
        }
        OneUser obj = new OneUser();
        obj.setPassword((String)oneUser.get("password"));
        obj.setPhone((String) oneUser.get("phone"));
        obj.setLoginName((String) oneUser.get("loginName"));
        obj.setGender((String) oneUser.get("gender"));
        obj.setWeixin((String) oneUser.get("weixin"));
        obj.setZhifubao((String) oneUser.get("zhifubao"));
        obj.setUpperUserRefId((String) oneUser.get("upperUserRefId"));
        obj.setUserName((String) oneUser.get("userName"));
        oneUserService.addOneUser(obj);
        jsonResult.setCode("1");
        return jsonResult;
    }

    /**
     * 用户登陆
     * @param request
     * @return
     */
    @RequestMapping(value = "/userLogin", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult userLogin(HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        OneUser oneUser=oneUserService.findByPhone(phone);

        if(oneUser==null){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机号码未注册！");
            return jsonResult;
        }
        if(!oneUser.getPassword().equals(password)){
            jsonResult.setCode("-1");
            jsonResult.setMsg("手机号码或密码错误！");
            return jsonResult;
        }

        String token = StringUtils.getUUID();
        cacheProvider.put(oneUser.getUserId(),token);

        jsonResult.setCode("1");
        Map<String, Object> data=MapUtils.beanToMap(oneUser);
        data.put("token",token);
        jsonResult.setData(data);
        return jsonResult;
    }


    /**
     * 获取验证码
     * @param request
     * @return
     */
    @RequestMapping(value = "/geetestRegister", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult geetestRegister(HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();

        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
                GeetestConfig.isnewfailback());
        String userid = "test";
        jsonResult.setCode("1");
        int gtServerStatus = gtSdk.preProcess(userid);
        jsonResult.setData(gtSdk.getResponseStr());
        //进行验证预处理
        return jsonResult;
    }

    /**
     * 退出登陆
     * @param request
     * @param token
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userLogout", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult userLogout(HttpServletRequest request,String token,String  userId) {
        JSONResult jsonResult = new JSONResult();
        if(!cacheProvider.get(userId).equals(token)){
            jsonResult.setCode("-2");
            jsonResult.setMsg("token失效|Invalid token");
            return jsonResult;
        }
        cacheProvider.remove(userId);
        jsonResult.setCode("1");
        jsonResult.setMsg("成功|success");
        return  jsonResult;
    }

}
